<template>
	<view class="circle-square" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
		<!-- 顶部搜索区域 -->
		<view class="search-section">
			<view class="search-header">
				<text class="page-title">圈子广场</text>
			</view>

			<view class="search-container">
				<view class="search-box">
					<view class="search-icon">🔍</view>
					<input class="search-input" v-model="searchKeyword" placeholder="搜索圈子名称..."
						@input="handleSearchInput" @confirm="handleSearch" />
					<view class="clear-btn" @click="clearSearch" v-if="searchKeyword">
						✕
					</view>
				</view>
				<!-- 我的圈子按钮移到搜索框右边 -->
				<view class="my-circle-btn" @click="goToMyCircle">
					<text class="my-circle-text">我的圈子</text>
				</view>
			</view>

			<!-- 快速筛选 -->
			<view class="filter-tabs">
				<view class="filter-tab" :class="{ active: activeFilter === filter.key }"
					v-for="filter in filterOptions" :key="filter.key" @click="setActiveFilter(filter.key)">
					{{ filter.label }}
				</view>
			</view>
		</view>

		<!-- 热门推荐区域 -->
		<view class="hot-section" v-if="!isSearching && hotCircles.length > 0">
			<view class="section-header">
				<text class="section-title">🔥 热门圈子</text>
				<text class="section-subtitle">人气最高的圈子</text>
			</view>
			<scroll-view class="hot-circles" scroll-x="true" show-scrollbar="false">
				<view class="hot-circle-item" v-for="circle in hotCircles" :key="circle.id"
					@click="handleCircleClick(circle)">
					<image :src="circle.circleAvatar" class="hot-circle-avatar" mode="aspectFill" />
					<text class="hot-circle-name">{{ circle.circleName }}</text>
					<text class="hot-circle-heat">{{ circle.heatScore }}🔥</text>
				</view>
			</scroll-view>
		</view>

		<!-- 圈子列表区域 -->
		<view class="circles-section">
			<view class="section-header" v-if="!isSearching">
				<text class="section-title">{{ getSectionTitle() }}</text>
				<text class="section-subtitle">共 {{ displayCircles.length }} 个圈子</text>
			</view>

			<view class="search-result-header" v-if="isSearching">
				<text class="search-result-text">
					{{ searchKeyword ? `"${searchKeyword}" 的搜索结果` : '全部圈子' }}
				</text>
				<text class="search-result-count">{{ displayCircles.length }} 个结果</text>
			</view>

			<!-- 加载状态 -->
			<view class="loading-container" v-if="loading">
				<view class="loading-spinner">🔄</view>
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 圈子列表 -->
			<view class="circles-list" v-else-if="displayCircles.length > 0">
				<CircleCard v-for="circle in displayCircles" :key="circle.id" :circle="circle"
					@click="handleCircleClick" />
			</view>

			<!-- 空状态 -->
			<view class="empty-container" v-else-if="!loading">
				<view class="empty-content">
					<text class="empty-icon">{{ getEmptyIcon() }}</text>
					<text class="empty-title">{{ getEmptyTitle() }}</text>
					<text class="empty-description">{{ getEmptyDescription() }}</text>
					<button class="refresh-btn" @click="refreshData">
						<text class="refresh-icon">🔄</text>
						<text>刷新数据</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 回到顶部按钮 -->
		<view class="back-to-top" v-if="showBackToTop" @click="scrollToTop">
			<text class="back-to-top-icon">↑</text>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
	import { onPageScroll } from '@dcloudio/uni-app'
	import { queryCircleByCircleName, getCircleList, getHotCircle } from '@/api/circle/circle'
	import type { CircleBasicInfo } from '@/api/circle/circle'
	import CircleCard from '../components/CircleCard.vue'
	import EmptyState from '../components/EmptyState.vue'

	// 获取屏幕边界到安全区域距离
	const { safeAreaInsets } = uni.getWindowInfo()

	// 响应式数据
	const allCircles = ref<CircleBasicInfo[]>([])
	const originalCircles = ref<CircleBasicInfo[]>([]) // 保存原始数据
	const hotCircles = ref<CircleBasicInfo[]>([])
	const searchKeyword = ref('')
	const loading = ref(false)
	const showBackToTop = ref(false)
	const activeFilter = ref('all')
	const searchTimeout = ref<NodeJS.Timeout | null>(null)

	// 筛选选项
	const filterOptions = [
		{ key: 'all', label: '全部' },
		{ key: 'hot', label: '热门' },
		{ key: 'new', label: '最新' },
		{ key: 'active', label: '活跃' }
	]

	// 计算属性
	const isSearching = computed(() => searchKeyword.value.trim() !== '')

	const displayCircles = computed(() => {
		let circles = [...allCircles.value]

		// 搜索筛选
		if (isSearching.value) {
			const keyword = searchKeyword.value.trim().toLowerCase()
			circles = circles.filter(circle =>
				circle.circleName.toLowerCase().includes(keyword) ||
				(circle.circleDescription && circle.circleDescription.toLowerCase().includes(keyword))
			)
		}

		// 排序筛选
		switch (activeFilter.value) {
			case 'hot':
				circles.sort((a, b) => (b.heatScore || 0) - (a.heatScore || 0))
				break
			case 'new':
				circles.sort((a, b) => new Date(b.createdTime).getTime() - new Date(a.createdTime).getTime())
				break
			case 'active':
				circles.sort((a, b) => (parseInt(b.postCount) || 0) - (parseInt(a.postCount) || 0))
				break
			default:
				// 默认按热度和成员数综合排序
				circles.sort((a, b) => {
					const scoreA = (a.heatScore || 0) + (parseInt(a.memberCount) || 0) * 0.1
					const scoreB = (b.heatScore || 0) + (parseInt(b.memberCount) || 0) * 0.1
					return scoreB - scoreA
				})
		}

		return circles
	})

	// 方法
	const loadAllCircles = async () => {
		try {
			loading.value = true
			const response = await getCircleList()
			if (response && response.rows) {
				allCircles.value = response.rows
				originalCircles.value = [...response.rows] // 保存原始数据
			}
		} catch (error) {
			console.error('加载圈子列表失败:', error)
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	const loadHotCircles = async () => {
		try {
			const response = await getHotCircle()
			if (response && response.data) {
				hotCircles.value = response.data.slice(0, 10) // 只显示前10个热门圈子
			}
		} catch (error) {
			console.error('加载热门圈子失败:', error)
		}
	}

	const handleSearchInput = () => {
		// 防抖搜索
		if (searchTimeout.value) {
			clearTimeout(searchTimeout.value)
		}

		searchTimeout.value = setTimeout(() => {
			if (searchKeyword.value.trim()) {
				performSearch()
			} else {
				// 如果搜索关键词为空，恢复原始数据
				allCircles.value = [...originalCircles.value]
			}
		}, 300)
	}

	const handleSearch = () => {
		if (searchTimeout.value) {
			clearTimeout(searchTimeout.value)
		}
		if (searchKeyword.value.trim()) {
			performSearch()
		} else {
			allCircles.value = [...originalCircles.value]
		}
	}

	const performSearch = async () => {
		const keyword = searchKeyword.value.trim()
		if (!keyword) return

		try {
			loading.value = true
			const response = await queryCircleByCircleName(keyword)
			if (response && response.rows) {
				// 搜索时不替换原始数据，而是使用搜索结果
				allCircles.value = response.rows
			} else {
				// 如果没有搜索结果，使用本地筛选
				allCircles.value = [...originalCircles.value]
			}
		} catch (error) {
			console.error('搜索失败:', error)
			// 搜索失败时使用本地筛选
			allCircles.value = [...originalCircles.value]
			uni.showToast({
				title: '搜索失败，使用本地筛选',
				icon: 'none'
			})
		} finally {
			loading.value = false
		}
	}

	const clearSearch = () => {
		searchKeyword.value = ''
		if (searchTimeout.value) {
			clearTimeout(searchTimeout.value)
		}
		// 恢复原始数据
		allCircles.value = [...originalCircles.value]
	}

	const setActiveFilter = (filterKey : string) => {
		activeFilter.value = filterKey
	}

	const handleCircleClick = (circle : CircleBasicInfo) => {
		// 跳转到圈子详情页
		uni.navigateTo({
			url: `/pages/circle/circleDetail/circleDetail?id=${circle.id}`
		})
	}

	const goToMyCircle = () => {
		// 跳转到我的圈子页面
		uni.navigateTo({
			url: '/pages/circle/myCircle'
		})
	}

	const refreshData = () => {
		loadAllCircles()
		loadHotCircles()
	}

	const scrollToTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		})
	}

	const getSectionTitle = () => {
		switch (activeFilter.value) {
			case 'hot': return '🔥 热门圈子'
			case 'new': return '✨ 最新圈子'
			case 'active': return '💬 活跃圈子'
			default: return '📋 全部圈子'
		}
	}

	const getEmptyIcon = () => {
		return isSearching.value ? '🔍' : '📭'
	}

	const getEmptyTitle = () => {
		return isSearching.value ? '没有找到相关圈子' : '暂无圈子数据'
	}

	const getEmptyDescription = () => {
		return isSearching.value
			? `试试搜索其他关键词，或者浏览全部圈子`
			: '当前还没有圈子，等待更多精彩内容'
	}

	// 监听页面滚动
	const handlePageScroll = (e : any) => {
		showBackToTop.value = e.scrollTop > 500
	}

	// 生命周期
	onMounted(() => {
		loadAllCircles()
		loadHotCircles()
	})

	// 页面滚动监听
	onPageScroll(handlePageScroll)

	// 页面销毁时清理
	onUnmounted(() => {
		if (searchTimeout.value) {
			clearTimeout(searchTimeout.value)
		}
	})
</script>

<style lang="scss" scoped>
	.circle-square {
		background: #f8f9fa;
		min-height: 100vh;
		padding-bottom: 40rpx;
	}

	.search-section {
		background: white;
		padding: 32rpx;
		margin-bottom: 20rpx;
		border-radius: 0 0 32rpx 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.search-header {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 32rpx;

		.page-title {
			font-size: 44rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.action-bar {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 24rpx;

		.my-circle-btn {
			display: flex;
			align-items: center;
			padding: 16rpx 24rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border-radius: 32rpx;

			.my-circle-text {
				color: white;
				font-size: 28rpx;
				margin-right: 8rpx;
			}

			.arrow {
				color: white;
				font-size: 24rpx;
			}
		}
	}

	.search-container {
		margin-bottom: 32rpx;
		display: flex;
		align-items: center;
		gap: 24rpx;

		.search-box {
			display: flex;
			align-items: center;
			background: #f5f5f5;
			border-radius: 48rpx;
			padding: 0 32rpx;
			height: 88rpx;
			flex: 1; /* 让搜索框占据剩余空间 */

			.search-icon {
				font-size: 32rpx;
				color: #999;
				margin-right: 16rpx;
			}

			.search-input {
				flex: 1;
				font-size: 32rpx;
				color: #333;
				background: transparent;
				border: none;
				outline: none;
			}

			.clear-btn {
				font-size: 28rpx;
				color: #999;
				padding: 8rpx;
			}
		}

		.my-circle-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 16rpx 24rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border-radius: 32rpx;
			white-space: nowrap; /* 防止文字换行 */

			.my-circle-text {
				color: white;
				font-size: 28rpx;
			}
		}
	}

	/* 移除原来的 action-bar 样式 */
	/* .action-bar {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 24rpx;

		.my-circle-btn {
			display: flex;
			align-items: center;
			padding: 16rpx 24rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border-radius: 32rpx;

			.my-circle-text {
				color: white;
				font-size: 28rpx;
				margin-right: 8rpx;
			}

			.arrow {
				color: white;
				font-size: 24rpx;
			}
		}
	} */

	.filter-tabs {
		display: flex;
		gap: 24rpx;

		.filter-tab {
			padding: 16rpx 32rpx;
			background: #f0f0f0;
			border-radius: 32rpx;
			font-size: 28rpx;
			color: #666;
			transition: all 0.3s ease;

			&.active {
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				color: white;
			}
		}
	}

	.hot-section {
		margin-bottom: 32rpx;
		padding: 0 32rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;

			.section-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.section-subtitle {
				font-size: 24rpx;
				color: #999;
			}
		}

		.hot-circles {
			white-space: nowrap;

			.hot-circle-item {
				display: inline-block;
				width: 160rpx;
				margin-right: 24rpx;
				text-align: center;
				background: white;
				border-radius: 24rpx;
				padding: 24rpx 16rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

				.hot-circle-avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 20rpx;
					margin-bottom: 12rpx;
				}

				.hot-circle-name {
					font-size: 24rpx;
					color: #333;
					display: block;
					margin-bottom: 8rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.hot-circle-heat {
					font-size: 20rpx;
					color: #ff6b35;
				}
			}
		}
	}

	.circles-section {
		padding: 0 32rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;

			.section-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.section-subtitle {
				font-size: 24rpx;
				color: #999;
			}
		}

		.search-result-header {
			margin-bottom: 24rpx;

			.search-result-text {
				font-size: 32rpx;
				color: #333;
				display: block;
				margin-bottom: 8rpx;
			}

			.search-result-count {
				font-size: 24rpx;
				color: #999;
			}
		}

		.loading-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 120rpx 0;

			.loading-spinner {
				font-size: 60rpx;
				animation: spin 1s linear infinite;
				margin-bottom: 24rpx;
			}

			.loading-text {
				font-size: 28rpx;
				color: #999;
			}
		}

		.circles-list {
			// CircleCard 组件自带样式
		}

		.empty-container {
			padding: 120rpx 60rpx;

			.empty-content {
				text-align: center;

				.empty-icon {
					font-size: 120rpx;
					margin-bottom: 40rpx;
					display: block;
				}

				.empty-title {
					font-size: 36rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 20rpx;
					display: block;
				}

				.empty-description {
					font-size: 28rpx;
					color: #666;
					line-height: 1.6;
					margin-bottom: 60rpx;
					display: block;
				}

				.refresh-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 24rpx 48rpx;
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: white;
					border-radius: 48rpx;
					border: none;
					font-size: 32rpx;
					margin: 0 auto;

					.refresh-icon {
						margin-right: 12rpx;
					}
				}
			}
		}
	}

	.back-to-top {
		position: fixed;
		bottom: 100rpx;
		right: 32rpx;
		width: 88rpx;
		height: 88rpx;
		background: rgba(102, 126, 234, 0.9);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
		z-index: 100;

		.back-to-top-icon {
			color: white;
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>